package net.unix8.server;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.json.JSONException;
import org.json.JSONObject;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import net.unix8.share.NetworkShare;

@Sharable
public class DataServerHandler extends ChannelInboundHandlerAdapter {
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) {
		ByteBuf in = (ByteBuf) msg;
		String cmd = null, host = null, data = null;
		int id = 0;
		int  bad = 0;//0 SUCCESS, 1 CMD ERROE,2 JSON ERROR

		try {
			int len = in.readableBytes();
			cmd = in.readBytes(len).toString(Charset.forName("UTF-8"));
			//System.out.println(cmd+"\n");
			JSONObject json = new JSONObject(cmd);
			host = json.optString("host",null).trim();
			cmd = json.optString("cmd",null).trim();
			id = json.optInt("id",-1);
			data = json.optString("data",null);

/*			System.out.print("ID:"+id+"\n");
			System.out.print("HOST:"+json.opt("host")+"\n");
			System.out.print("CMD:"+json.opt("cmd")+"\n");
			System.out.print("DATA:"+json.opt("data")+"\n");
*/
		} catch(Exception e) {
			ReferenceCountUtil.release(msg); // (2)
			bad = 2;
			e.printStackTrace();
		}
		
		if(bad == 0) return;
		JSONObject studentJSONObject = new JSONObject();  
		String errorString = "UNKNOWN ERROR";
		try {  
			studentJSONObject.put("host", host);
			studentJSONObject.put("id", id);  
			studentJSONObject.put("cmd", "data"); 
			studentJSONObject.put("status", false);  
			if(bad == 1){
				errorString = "CMD ERROR";
			}else if(bad == 2){
				errorString = "JSON ERROR";
			}
			studentJSONObject.put("data", errorString);  
		} catch (JSONException e) {  
			e.printStackTrace();  
		}  
		final ByteBuf firstMessage;
		firstMessage = Unpooled.buffer(100);
		firstMessage.writeCharSequence(studentJSONObject.toString(), Charset.forName("UTF-8"));
		ctx.writeAndFlush(firstMessage);
		firstMessage.release();

		/*
		String txt = "Hello,I'm client.";
		final ByteBuf firstMessage;
		firstMessage = Unpooled.buffer(100);
        firstMessage.writeCharSequence(txt, Charset.forName("UTF-8"));
		Channel remoteChannel = NetworkShare.clientGroup.find(ctx.channel().id());
		if(remoteChannel != null){
			System.out.println("SEND JSON SUCCESS:");
			remoteChannel.writeAndFlush(firstMessage);
		}*/
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) {
		ctx.flush();
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		InetSocketAddress insocket = (InetSocketAddress) ctx.channel()
				.remoteAddress();
		String clientIP = insocket.getAddress().getHostAddress();
		System.out.println("4444 Disconnected ip:"+clientIP);
		NetworkShare.clientGroup.remove(ctx.channel());
		super.channelInactive(ctx);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		InetSocketAddress insocket = (InetSocketAddress) ctx.channel()
				.remoteAddress();
		String clientIP = insocket.getAddress().getHostAddress();
		System.out.println("4444 Exception ip:"+clientIP);
		NetworkShare.clientGroup.remove(ctx.channel());
		// Close the connection when an exception is raised.
		cause.printStackTrace();
		ctx.close();
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception{
		InetSocketAddress insocket = (InetSocketAddress) ctx.channel()
				.remoteAddress();
		String clientIP = insocket.getAddress().getHostAddress();
		System.out.println("4444 Establised :"+clientIP);
		NetworkShare.clientGroup.add(ctx.channel());
		super.channelActive(ctx);

	}

}
